﻿using System;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using SW.Lite.BLL.Master;
using SW.Lite.Core.Attributes;
using SW.Lite.Core.Authority;
using SW.Lite.Infrastructure.Common;
using SW.Lite.Infrastructure.Helpers;
using SW.Lite.Model.Master;

namespace SW.Lite.WebSite.Areas.Master.Controllers
{
    /// <summary>
    /// Class AdminController.
    /// </summary>
    public class MAdminController : BaseController
    {
        /// <summary>
        /// Indexes the specified page.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <returns>ActionResult.</returns>
        [Menu(MenuCode = "MAdminManage")]
        public ActionResult Index(int page)
        {
            var list = Admin.All(page, PageSize);
            ViewBag.RecordCount = list.AllCount;
            return View(list);
        }

        /// <summary>
        /// Faces the upload.
        /// </summary>
        /// <returns>ActionResult.</returns>
        [Menu(MenuCode = "MAdminManage")]
        public ActionResult FaceUpload()
        {
            return View();
        }

        /// <summary>
        /// Faces the upload post.
        /// </summary>
        /// <returns>ActionResult.</returns>
        [HttpPost]
        [Menu(MenuCode = "MAdminManage")]
        public ActionResult FaceUploadPost()
        {
            var file = Request.Files["faceImg"];
            if (file == null || file.ContentLength <= 0) return View("FaceUpload");

            var fileFolder = ConfigHelper.Instance.Upload.FaceFolder + "/" + DateTime.Now.Year;
            var absFileFolder = Server.MapPath(fileFolder);
            if (!Directory.Exists(absFileFolder))
                Directory.CreateDirectory(absFileFolder);

            var filePath = fileFolder + "/" + RandomHelper.Instance.RandomString("******") + ".jpg";
            file.SaveAs(Server.MapPath(filePath));
            ViewBag.FilePath = filePath.Replace("~", "");
            return View("FaceUpload");
        }

        /// <summary>
        /// Adds the specified admin.
        /// </summary>
        /// <param name="admin">The admin.</param>
        /// <returns>JsonResult.</returns>
        [HttpPost]
        [Button(MenuCode = "MAdminManage", ButtonCode = "Add", IsAjax = true)]
        public JsonResult Add(AdminModel admin)
        {
            admin.PasswordSalt = RandomHelper.Instance.RandomString("******");
            admin.Password = SecurityHelper.Instance.EncryptPassword(admin.Password, admin.PasswordSalt);
            admin.LastLoginTime = DateTime.Now;
            admin.LoginCount = 0;
            admin.LastLoginIP = "0.0.0.0";

            var result = Admin.Insert(admin);
            return result ? new JsonResult { Data = new ExecuteResult { Result = true } } : new JsonResult { Data = new ExecuteResult { Result = false, Message = result.Message } };
        }

        /// <summary>
        /// Deletes the specified ids.
        /// </summary>
        /// <param name="ids">The ids.</param>
        /// <returns>JsonResult.</returns>
        [HttpPost]
        [Button(MenuCode = "MAdminManage", ButtonCode = "DeleteAll", IsAjax = true)]
        public JsonResult Delete(string ids)
        {
            if (ids.Length <= 0)
                return new JsonResult { Data = new ExecuteResult { Message = "请选择删除的人员" } };

            var et = ids.Split(',').Select(n => Convert.ToInt32(n));

            var result = Admin.Delete(et.ToArray());
            return result ? new JsonResult { Data = new ExecuteResult { Result = true } } : new JsonResult { Data = new ExecuteResult { Result = false, Message = result.Message } };
        }

        /// <summary>
        /// Roles the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>JsonResult.</returns>
        [Button(MenuCode = "MAdminManage", ButtonCode = "Role")]
        public ActionResult Role(int id)
        {
            var admin = Admin.Single(id);
            var adminRoles = Lite.BLL.Master.Role.GetRolesByAdminId(id);
            var roles = Lite.BLL.Master.Role.All();

            var roleList = roles.Select(n => new
            {
                RoleID = n.Id,
                name = n.Title,
                @checked = adminRoles.Select(r => r.Id).Contains(n.Id)
            }).ToList();

            ViewBag.Roles = Newtonsoft.Json.JsonConvert.SerializeObject(roleList);

            return View(admin);
        }

        /// <summary>
        /// Saves the role.
        /// </summary>
        /// <param name="adminID">The admin identifier.</param>
        /// <param name="jsonRole">The json role.</param>
        /// <returns>JsonResult.</returns>
        [Button(MenuCode = "MAdminManage", ButtonCode = "Role", IsAjax = true)]
        public JsonResult SaveRole(int adminID, string jsonRole)
        {
            var roles = jsonRole.Split(',');

            var result = Admin.AddAdminRoles(adminID, true, roles.Select(r => Convert.ToInt32(r)).ToArray());

            return result ? new JsonResult { Data = new ExecuteResult { Result = true } } : new JsonResult { Data = new ExecuteResult { Result = false, Message = result.Message } };
        }
    }
}
